<template>
  <div class="medical-card-management">
    <el-card class="page-container">
      <template #header>
        <div class="card-header">
          <span>慢性病证管理</span>
          <el-button type="primary" @click="handleAddCard">新增慢病证</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="农合证号">
            <el-input v-model="searchForm.ruralCardNo" placeholder="请输入农合证号" clearable />
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input v-model="searchForm.cardId" placeholder="请输入身份证号" clearable />
          </el-form-item>
          <el-form-item label="疾病名称">
            <el-select v-model="searchForm.diseaseName" placeholder="请选择疾病" clearable style="width: 300px;">
              <el-option
                v-for="disease in diseaseList"
                :key="disease.diseaseCode"
                :label="disease.diseaseCode + ' - ' + disease.diseaseName"
                :value="disease.diseaseName"
                style="min-width: 250px;"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 慢病证信息表格 -->
      <el-table :data="filteredCardList" border style="width: 100%">
        <el-table-column prop="ruralCardNo" label="农合证号" width="120" />
        <el-table-column prop="diseaseCode" label="慢病编码" width="120" />
        <el-table-column prop="cardId" label="身份证号" width="180" />
        <el-table-column prop="diseaseName" label="疾病名称" width="150" />
        <el-table-column prop="startTime" label="起始时间" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="终止时间" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
            <el-button
                size="small"
                type="success"
                @click="handlePrint(scope.row)"
            >打印</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑慢病证对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑慢病证' : '新增慢病证'"
        width="40%"
    >
      <el-form :model="currentCard" label-width="100px" :rules="rules" ref="cardForm">
        <el-form-item label="农合证号" prop="ruralCardNo">
          <el-input v-model="currentCard.ruralCardNo" placeholder="请输入农合证号" />
        </el-form-item>
        <el-form-item label="身份证号" prop="cardId">
          <el-input v-model="currentCard.cardId" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="疾病名称" prop="diseaseName">
          <el-select v-model="currentCard.diseaseName" placeholder="请选择疾病" style="min-width: 250px; width: 100%;" @change="handleDiseaseChange" filterable>
            <el-option
              v-for="disease in diseaseList"
              :key="disease.diseaseCode"
              :label="disease.diseaseCode + ' - ' + disease.diseaseName"
              :value="disease.diseaseName"
              style="min-width: 200px;"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期" prop="dateRange">
          <el-date-picker
            v-model="currentCard.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCard">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 打印预览对话框 -->
    <el-dialog
        v-model="printDialogVisible"
        title="慢病证打印预览"
        width="60%"
    >
      <div class="print-area" ref="printArea">
        <h2 class="print-title">慢性病证</h2>
        <div class="print-content">
          <div class="print-item">
            <span class="label">农合证号：</span>
            <span>{{ printData.ruralCardNo }}</span>
          </div>
          <div class="print-item">
            <span class="label">慢病编码：</span>
            <span>{{ printData.diseaseCode }}</span>
          </div>
          <div class="print-item">
            <span class="label">身份证号：</span>
            <span>{{ printData.cardId }}</span>
          </div>
          <div class="print-item">
            <span class="label">疾病名称：</span>
            <span>{{ printData.diseaseName }}</span>
          </div>
          <div class="print-item">
            <span class="label">有效期：</span>
            <span>{{ formatDate(printData.startTime) }} 至 {{ formatDate(printData.endTime) }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="printDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="doPrint">确认打印</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 疾病列表
const diseaseList = ref([])

// 获取疾病列表
const fetchDiseaseList = async () => {
  const { data } = await axios.get('/disease/list')
  if (data.code === 200) {
    diseaseList.value = data.data.map(item => ({
      diseaseName: item.diseaseName,
      diseaseCode: item.diseaseCode
    }))
  }
}

// 表单验证规则
const rules = {
  ruralCardNo: [
    { required: true, message: '请输入农合证号', trigger: 'blur' },
    { pattern: /^NH\d{9}$/, message: '农合证号格式：NH+9位数字', trigger: 'blur' }
  ],
  cardId: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  diseaseName: [
    { required: true, message: '请选择疾病名称', trigger: 'change' }
  ],
  dateRange: [
    { required: true, message: '请选择有效期', trigger: 'change' }
  ]
}

const cardList = ref([])
const dialogVisible = ref(false)
const printDialogVisible = ref(false)
const isEdit = ref(false)
const cardForm = ref(null)
const printArea = ref(null)

const searchForm = ref({
  ruralCardNo: '',
  cardId: '',
  diseaseName: ''
})

const currentCard = ref({
  id: 0,
  ruralCardNo: '',
  diseaseCode: '',
  cardId: '',
  diseaseName: '',
  dateRange: []
})

const printData = ref({})

// 过滤后的慢病证列表
const filteredCardList = computed(() => {
  return cardList.value.filter(item => {
    const matchRuralCard = !searchForm.value.ruralCardNo || 
      item.ruralCardNo.includes(searchForm.value.ruralCardNo)
    const matchCardId = !searchForm.value.cardId || 
      item.cardId.includes(searchForm.value.cardId)
    const matchDisease = !searchForm.value.diseaseName || 
      item.diseaseName === searchForm.value.diseaseName
    return matchRuralCard && matchCardId && matchDisease
  })
})

// 日期格式化
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}

// 查询慢病证列表
const fetchCardList = async () => {
  const params = {
    ruralCardNo: searchForm.value.ruralCardNo,
    cardId: searchForm.value.cardId,
    diseaseName: searchForm.value.diseaseName
  }
  const { data } = await axios.get('/medicalCard/list', { params })
  if (data.code === 200) {
    cardList.value = data.data.map(item => ({
      ...item,
      dateRange: [item.startTime, item.endTime]
    }))
  }
}

// 初始化
onMounted(() => {
  fetchDiseaseList()
  fetchCardList()
})

// 查询
const handleSearch = () => {
  fetchCardList()
}

// 重置
const resetSearch = () => {
  searchForm.value = {
    ruralCardNo: '',
    cardId: '',
    diseaseName: ''
  }
  fetchCardList()
}

// 新增
const handleAddCard = () => {
  isEdit.value = false
  currentCard.value = {
    id: 0,
    ruralCardNo: '',
    diseaseCode: '',
    cardId: '',
    diseaseName: '',
    dateRange: []
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = (index, row) => {
  isEdit.value = true
  currentCard.value = {
    ...row,
    dateRange: [row.startTime, row.endTime]
  }
  dialogVisible.value = true
}

// 删除
const handleDelete = (index, row) => {
  ElMessageBox.confirm('确认删除该慢病证信息吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const { data } = await axios.delete(`/medicalCard/delete/${row.id}`)
      if (data.code === 200) {
        ElMessage.success('删除成功')
        fetchCardList()
      } else {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 打印
const handlePrint = (row) => {
  printData.value = { ...row }
  printDialogVisible.value = true
}

// 执行打印
const doPrint = () => {
  const content = printArea.value.innerHTML
  const printWindow = window.open('', '_blank')
  printWindow.document.write(`
    <html>
      <head>
        <title>慢病证打印</title>
        <style>
          .print-title { text-align: center; }
          .print-content { padding: 20px; }
          .print-item { margin: 10px 0; }
          .label { font-weight: bold; margin-right: 10px; }
        </style>
      </head>
      <body>${content}</body>
    </html>
  `)
  printWindow.document.close()
  printWindow.print()
  printDialogVisible.value = false
}

// 提交（新增/编辑）
const submitCard = () => {
  if (!cardForm.value) return
  cardForm.value.validate(async (valid) => {
    if (valid) {
      const [startTime, endTime] = currentCard.value.dateRange
      const formData = {
        ...currentCard.value,
        startTime,
        endTime
      }
      if (isEdit.value) {
        // 编辑
        const { data } = await axios.put('/medicalCard/update', formData)
        if (data.code === 200) {
          ElMessage.success('慢病证信息更新成功')
          dialogVisible.value = false
          fetchCardList()
        } else {
          ElMessage.error('更新失败')
        }
      } else {
        // 新增
        const { data } = await axios.post('/medicalCard/add', formData)
        if (data.code === 200) {
          ElMessage.success('慢病证添加成功')
          dialogVisible.value = false
          fetchCardList()
        } else {
          ElMessage.error('添加失败')
        }
      }
    }
  })
}

// 选择疾病时自动填充编码
const handleDiseaseChange = (val) => {
  const selected = diseaseList.value.find(d => d.diseaseName === val)
  currentCard.value.diseaseCode = selected ? selected.diseaseCode : ''
}
</script>

<style scoped>
.medical-card-management {
  padding: 20px;
}

.page-container {
  margin: 0;
  min-height: calc(100vh - 140px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.search-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.el-table {
  margin-top: 20px;
}

/* 打印样式 */
.print-title {
  text-align: center;
  margin-bottom: 30px;
}

.print-content {
  padding: 20px;
}

.print-item {
  margin: 15px 0;
  line-height: 24px;
}

.print-item .label {
  font-weight: bold;
  margin-right: 10px;
  display: inline-block;
  width: 100px;
}
</style>